<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8" />
  <title>验证码登录</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      padding: 50px;
      background-color: #f4f4f4;
    }
    .login-box {
      max-width: 400px;
      margin: auto;
      background: white;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }
    input[type="text"],
    input[type="password"] {
      width: 100%;
      padding: 10px;
      margin-bottom: 15px;
      border: 1px solid #ccc;
      border-radius: 4px;
    }
    img {
      cursor: pointer;
      width: 120px;
      height: 40px;
      vertical-align: middle;
    }
    button {
      padding: 10px 20px;
      background-color: #007bff;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }
    button:hover {
      background-color: #0056b3;
    }
  </style>
</head>
<body>

<div class="login-box">
  <h3>登录</h3>
  <input type="text" id="username" placeholder="用户名" />
  <input type="password" id="password" placeholder="密码" />
  <input type="text" id="code" placeholder="验证码" />

  <!-- 验证码图片 -->
  <img id="captcha-img" src="" alt="验证码" onclick="refreshCaptcha()" />

  <button onclick="submitLogin()">登录</button>
</div>

<script>
  let uuid = "";

  // 获取验证码
  async function refreshCaptcha() {
    const response = await fetch('/captcha/getCaptcha');
    const data = await response.json();
    if (data.code === 200) {
      document.getElementById('captcha-img').src = data.data.img;
      uuid = data.data.uuid;
    } else {
      alert("获取验证码失败：" + data.msg);
    }
  }

  // 提交登录
  async function submitLogin() {
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const code = document.getElementById('code').value;

    const response = await fetch('/captcha/checkCaptcha', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username,
        password,
        uuid,
        code
      })
    });

    const result = await response.json();
    if (result.code === 200) {
      alert("登录成功！Token: " + result.data);
      // 这里可以将 token 存入 localStorage 或跳转页面
    } else {
      alert("登录失败：" + result.msg);
      refreshCaptcha(); // 刷新验证码
    }
  }

  // 初始化加载验证码
  window.onload = refreshCaptcha;
</script>

</body>
</html>
